import time
import sys
import os
import math
import datetime
import pylab as plt
import numpy as np

from params import *


STEP = 1
XLBL = 'Days'
#STEP = 7
#XLBL = 'Weeks'
#STEP = 30
#XLBL = 'Months'
THRESHOLD = 0
MAX = 360/STEP
#MAX = 600/STEP
SPLIT = 200/STEP

def get_activity(d1,d2):
    format = "%Y-%m-%d"
    d1 = datetime.date(*map(int,d1.split('-')))
    d2 = datetime.date(*map(int,d2.split('-')))
    delta = (d2-d1).days
    delta /= STEP
    return delta
    
def get_age(d1,d2):
    format = "%Y-%m-%d"
    d1 = datetime.date(*map(int,d1.split('-')))
    d2 = datetime.date(2010,8,8)
    delta = (d2-d1).days
    delta /= STEP
    return delta

file = os.path.join(WORKDIR, 'gowalla', 'stats', 'gowalla_user_activity.txt')

age_values = []
activity_values = []
for line in open(file):
    user, d1, d2, places,checkins = line.strip().split()
    activity_values.append(get_activity(d1,d2))
    age_values.append(get_age(d1,d2))


activity_values.sort()
print 'median activity ', activity_values[len(activity_values)//2]
print 'average activity ', float(sum(activity_values))/len(activity_values)

age_values.sort()
print 'median age ', age_values[len(age_values)//2]
print 'average age ', float(sum(age_values))/len(age_values)

activity_values = filter(lambda x: MAX>=x>=THRESHOLD,activity_values)
age_values = filter(lambda x: MAX>=x>=THRESHOLD,age_values)
print 'activity'
v = sorted(activity_values)
avg_act = float(sum(activity_values))/len(activity_values)
print avg_act
print max(activity_values)

print 'age'
v = sorted(age_values)
avg_age = float(sum(age_values))/len(age_values)
print avg_age
print max(age_values)

hp_ac,hb_ac,xx = plt.hist(activity_values, 
        bins=np.array(range(min(activity_values),max(activity_values))),
        normed=True,log=True,cumulative=-1)
plt.close()
hb_ac = hb_ac[:-1]

hp_ac2,hb_ac2,xx = plt.hist(activity_values, 
        bins=np.array(range(min(activity_values),max(activity_values))),
        normed=True,cumulative=1)
plt.close()
hb_ac2 = hb_ac2[:-1]

hp_ag,hb_ag,xx = plt.hist(age_values, 
        bins=np.array(range(min(age_values),max(age_values))),
        normed=False)
plt.close()
hb_ag = hb_ag[:-1]

hp_ag2,hb_ag2,xx = plt.hist(age_values, 
        bins=np.array(range(min(age_values),max(age_values))),
        normed=True,cumulative=1)
plt.close()
hb_ag2 = hb_ag2[:-1]

first_half_x = []
first_half_y = []
second_half_x = []
second_half_y = []
for a,b in zip(hb_ac,hp_ac):
    if a <= SPLIT:
        first_half_x.append(a)
        first_half_y.append(math.log(b))
    else:
        second_half_x.append(a)
        second_half_y.append(math.log(b))

first_p= plt.polyfit(first_half_x,first_half_y,1)
fitted1 = map(math.exp,plt.polyval(first_p,first_half_x))
print first_p

second_p = plt.polyfit(second_half_x,second_half_y,2)
print second_p
fitted2 = map(math.exp,plt.polyval(second_p,second_half_x))
#fitted2[0] = fitted1[-1]

plt.figure()
plt.clf()
plt.axes(FIG_AXES2)
plt.plot(hb_ag,hp_ag,'k-')
plt.grid(True)
x1,x2,y1,y2 = plt.axis()
plt.axis([0,MAX,y1,y2])
plt.ylabel('PDF')
plt.xlabel(XLBL)
plt.savefig('gowalla_dist_age_pdf.pdf')
plt.close()


plt.figure()
plt.clf()
plt.axes(FIG_AXES2)
plt.semilogy(hb_ac,hp_ac,'cx')
plt.semilogy(first_half_x,fitted1,'k--')
plt.semilogy(second_half_x,fitted2,'k--')
#plt.axvline(SPLIT, #ymax=fitted1[-1],
#        linestyle='--',color='k')
plt.legend(['Data', 'Fit'],
#    r'$e^{-\lambda_1 x}$',
#    r'$e^{-\lambda_2 x^2}$'],
        loc = 'lower left',numpoints=1)
plt.axis([0,MAX,0,1])
plt.ylabel('CCDF')
plt.xlabel(XLBL)
plt.grid(True)
plt.savefig('gowalla_dist_activity_ccdf.pdf')
plt.close()

plt.figure()
plt.clf()
plt.axes(FIG_AXES2)
plt.plot(hb_ag2,hp_ag2,'k-')
plt.plot(hb_ac2,hp_ac2,'k--')
plt.grid(True)
x1,x2,y1,y2 = plt.axis()
plt.axis([0,MAX,0,1])
plt.ylabel('CDF')
plt.xlabel(XLBL)
plt.legend(['Account age', 'Account activity span'],
        loc='lower right', numpoints=1)
plt.savefig('gowalla_dist_age_activity_cdf.pdf')
plt.close()

#plt.figure()
#plt.clf()
#plt.axes(FIG_AXES2)
#plt.plot(hb_ag2,hp_ag2,'k-')
#plt.grid(True)
#plt.axis([0,MAX,0,1])
#plt.ylabel('CDF')
#plt.xlabel(XLBL)
#plt.savefig('dist_age_cdf.pdf')
#plt.close()
